const connection = require('../app/database')
class AttrService {
  async getCateAttr(id, sel) {
    const statement = `
      SELECT id attr_id,attr_name,cat_id,attr_sel,attr_write,attr_vals 
      FROM attribute WHERE cat_id = ? AND attr_sel = ?;
    `
    const [res] = await connection.execute(statement,[id,sel])
    return res

  }
  async addAttr(id, name, sel, vals) {
    const val = vals || ''
    const statement = `
      INSERT INTO attribute (cat_id,attr_name,attr_sel,attr_vals)
      VALUES (?,?,?,?)
    `
    const [res] = await connection.execute(statement, [id, name, sel, val])
    return res
  }
  async getAttr(id) {
    const statement = `
      SELECT * FROM attribute WHERE id = ?;
    `
    const [res] = await connection.execute(statement, [id])
    return res
  }
  async removeAttr(cat_id, attr_id) {
    const statement = `
      DELETE FROM attribute WHERE id = ? AND cat_id = ?;
    `
    const [res] = await connection.execute(statement, [attr_id, cat_id])
    return res
  }
  async getAttrById(cat_id, attr_id) {
    const statement = `
      SELECT * FROM attribute WHERE cat_id = ? AND id = ?;
    `
    const [res] = await connection.execute(statement,[cat_id,attr_id])
    return res
  }
  async updateAttr(catId, attrId, attr_name, attr_sel, attr_vals) {
    const val = attr_vals || ''
    const sql = `
      UPDATE attribute SET attr_name = ?,attr_sel = ?,attr_vals = ?
      WHERE id = ? AND cat_id = ?;
    `
    console.log(catId, attrId, attr_name, attr_sel, val);
    const [res] = await connection.execute(sql, [attr_name, attr_sel, val, attrId, catId])
    return res
  }
}
module.exports = new AttrService()